package com.seeyon.apps.u8cloud.manager;


import com.seeyon.apps.common.utils.JDBCAgentUtils;
import com.seeyon.apps.u8cloud.model.VoucherRecord;
import com.seeyon.cap4.form.bean.FormBean;
import com.seeyon.cap4.form.bean.FormDataMasterBean;
import com.seeyon.cap4.form.bean.FormFieldBean;
import com.seeyon.cap4.form.bean.FormTableBean;
import com.seeyon.cap4.form.service.CAP4FormManager;
import com.seeyon.cap4.soap.bean.AttachmentInfoBean;
import com.seeyon.ctp.common.AppContext;
import com.seeyon.ctp.common.ctpenumnew.manager.EnumManager;
import com.seeyon.ctp.common.log.CtpLogFactory;
import com.seeyon.ctp.util.Strings;
import com.seeyon.ctp.util.annotation.Inject;
import com.seeyon.ctp.util.json.JSONUtil;
import com.seeyon.v3x.services.form.FormFactory;
import com.seeyon.v3x.services.form.FormUtils;
import com.seeyon.v3x.services.form.bean.FormExport;
import org.apache.commons.logging.Log;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * @ClassName : VoucherRecordManagerImpl
 * @Description :
 * @CreateDate : 2025/5/19 9:44
 * @Author : CheungHowrAn
 * @Version : 1.0.0
 * @PackageName com.seeyon.apps.u8cloud.manager
 * @Project : BSiEE本涩_A8_V9.0SP1
 */
public class VoucherRecordManagerImpl implements VoucherRecordManager {
    private static final Log log = CtpLogFactory.getLog(VoucherRecordManager.class);
    @Inject
    private EnumManager enumManagerNew;
    @Inject
    private FormFactory formFactory;
    @Inject
    private CAP4FormManager cap4FormManager;
    private static final String FORM_CODE = AppContext.getSystemProperty("u8cloud.formCode");
    private static final String LOGIN_NAME = AppContext.getSystemProperty("u8cloud.loginName");

    /**
     * @MethodName getTableName
     * @Description 获取数据库表名
     * @return: java.lang.String
     * @Author CheungHowrAn
     * @Date 2024/4/11 11:19
     */
    public String getTableName() {
        String tableName = null;
        try {
            FormBean formBean = cap4FormManager.getFormByFormCode(FORM_CODE);
            tableName = formBean.getMasterTableBean().getTableName();
        } catch (Exception e) {
            log.error("获取表名异常：", e);
        }
        return tableName;
    }

    /**
     * @MethodName: getSuccessDataIdList
     * @Description:
     * @CreateDate: 2024/12/27 16:04
     * @Author: CheungHowrAn
     * @Params []
     * @ParamType []
     * @Return java.util.List<java.lang.Long>
     */
    public List<Long> getSuccessDataIdList() {
        List<Long> successDataIdList = new ArrayList<>();
        try {
            FormBean formBean = cap4FormManager.getFormByFormCode(FORM_CODE);
            FormFieldBean formFieldBean = formBean.getFieldBeanByDisplay("生成状态");
            FormFieldBean dataIdBean = formBean.getFieldBeanByDisplay("OA数据ID");
            StringBuffer sql = new StringBuffer();
            sql.append(" SELECT ");
            sql.append(" T1.").append(dataIdBean.getName()).append(" AS id");
            sql.append(" FROM ");
            sql.append(formFieldBean.getOwnerTableName() + " T1");
            sql.append(" WHERE ");
            sql.append(" T1.").append(formFieldBean.getName()).append("='成功'");
            log.info("查询SQL:" + sql);
            List<Map<String, Object>> list = JDBCAgentUtils.query(sql.toString());
            if (list != null && list.size() > 0) {
                for (Map<String, Object> map : list) {
                    successDataIdList.add(Long.valueOf(map.get("id").toString()));
                }
            }
        } catch (Exception e) {
            log.error("获取成功数据ID异常：", e);
        }
        return successDataIdList;
    }

    /**
     * @MethodName: getRecordIdByDataId
     * @Description: 根据OA数据主键获取记录ID
     * @CreateDate: 2024/12/27 16:32
     * @Author: CheungHowrAn
     * @Params [dataId]
     * @ParamType [java.lang.String]
     * @Return java.lang.Long
     */
    public Long getRecordIdByDataId(String dataId) {
        Long recordId = null;
        try {
            FormBean formBean = cap4FormManager.getFormByFormCode(FORM_CODE);
            FormFieldBean formFieldBean = formBean.getFieldBeanByDisplay("OA数据ID");
            StringBuffer sql = new StringBuffer();
            sql.append(" SELECT T1.ID ");
            sql.append(" FROM ");
            sql.append(formFieldBean.getOwnerTableName() + " T1");
            sql.append(" WHERE ");
            sql.append(" T1.").append(formFieldBean.getName()).append("='").append(dataId).append("'");
            log.info("查询SQL:" + sql);
            List<Map<String, Object>> list = JDBCAgentUtils.query(sql.toString());
            if (Strings.isNotEmpty(list)) {
                recordId = Long.valueOf(list.get(0).get("id").toString());
            }
        } catch (Exception e) {
            log.error("根据OA数据主键获取记录ID异常：", e);
        }
        return recordId;
    }

    /**
     * @MethodName: getNeedPushRecordIdList
     * @Description:
     * @CreateDate: 2024/12/27 16:04
     * @Author: CheungHowrAn
     * @Params []
     * @ParamType []
     * @Return java.util.List<java.lang.Long>
     */
    public List<Long> getNeedPushRecordIdList() {

        List<Long> failDataIdList = new ArrayList<>();
        try {
            FormBean formBean = cap4FormManager.getFormByFormCode(FORM_CODE);
            FormFieldBean formFieldBean = formBean.getFieldBeanByDisplay("生成状态");
            StringBuffer sql = new StringBuffer();
            sql.append(" SELECT T1.ID ");
            sql.append(" FROM ");
            sql.append(formFieldBean.getOwnerTableName() + " T1");
            sql.append(" WHERE ");
            sql.append(" T1.").append(formFieldBean.getName()).append("!='成功'");
            sql.append(" OR ").append(" T1.").append(formFieldBean.getName()).append(" IS NULL");

            log.info("查询SQL:" + sql);
            List<Map<String, Object>> list = JDBCAgentUtils.query(sql.toString());
            if (list != null && list.size() > 0) {
                for (Map<String, Object> map : list) {
                    failDataIdList.add(Long.valueOf(map.get("id").toString()));
                }
            }
        } catch (Exception e) {
            log.error("获取失败数据ID异常：", e);
        }
        return failDataIdList;
    }

    public void saveDockingRecords(VoucherRecord voucherRecord) {
        try {
            //如果后续还要增加参数 都通过 Map<String,Object> relevantParam 来传递
            Map<String, Object> relevantParam = new HashMap();

            //表单正文附件ID  值为 JSONUtil.toJSONString(new ArrayList<AttachmentInfoBean>());
            List<AttachmentInfoBean> attachmentList = new ArrayList<>();
            if (Strings.isNotEmpty(attachmentList)) {
                relevantParam.put("formContentAtt", JSONUtil.toJSONString(attachmentList));
            }
            FormBean formBean = cap4FormManager.getFormByFormCode(FORM_CODE);
            //主表字段
            FormTableBean masterTableBean = formBean.getMasterTableBean();
            Map<String, Object> mainDataMap = new LinkedHashMap<String, Object>();
            //要修改的底表字段对象
            mainDataMap.put(formBean.getFieldBeanByDisplay("OA数据ID").getName(), voucherRecord.getDataId());
            mainDataMap.put(formBean.getFieldBeanByDisplay("OA表单ID").getName(), voucherRecord.getFormId());
            mainDataMap.put(formBean.getFieldBeanByDisplay("OA数据标题").getName(), voucherRecord.getSubject());
            mainDataMap.put(formBean.getFieldBeanByDisplay("凭证ID").getName(), voucherRecord.getVoucherId());
            mainDataMap.put(formBean.getFieldBeanByDisplay("凭证编号").getName(), voucherRecord.getVoucherCode());
            mainDataMap.put(formBean.getFieldBeanByDisplay("生成状态").getName(), voucherRecord.getStatus());
            mainDataMap.put(formBean.getFieldBeanByDisplay("请求地址").getName(), voucherRecord.getServiceUrl());
            mainDataMap.put(formBean.getFieldBeanByDisplay("请求参数").getName(), voucherRecord.getParams());
            mainDataMap.put(formBean.getFieldBeanByDisplay("返回结果").getName(), voucherRecord.getResult());
            mainDataMap.put(formBean.getFieldBeanByDisplay("推送时间").getName(), voucherRecord.getCreateDate());
            FormDataMasterBean dataMasterBean = new FormDataMasterBean(mainDataMap, masterTableBean);
            FormExport formExport = FormUtils.createFormExport(formBean.getId(), dataMasterBean);
            if (formFactory == null) {
                formFactory = (FormFactory) AppContext.getBean("formFactory");
            }
            if (relevantParam.size() > 0) {
                formFactory.importBusinessForm(LOGIN_NAME, FORM_CODE, formExport, null, relevantParam);

            } else {
                Map<String, Object> relevant = new HashMap<String, Object>();
                formFactory.importBusinessForm(LOGIN_NAME, FORM_CODE, formExport, null, relevant);
            }
        } catch (Exception e) {
            log.error("创建日志数据异常：", e);
        }
    }


}
